﻿namespace Vboot.Core.Module.Sys;

[ApiDescriptionSettings("Sys", Tag = "合作伙伴-业务分类")]
public class SysCoopCateApi : IDynamicApiController
{
    private readonly SysCoopCateService _service;

    public SysCoopCateApi(SysCoopCateService service)
    {
        _service = service;
    }

    /// <summary>
    /// 获取所有分类-用于分类选择下拉框
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTreea()
    {
        var trees =await  _service.repo.Context.SqlQueryable<Ztree>
                ("select id,pid,name from sys_coop_cate order by ornum")
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return trees;
    }

    /// <summary>
    /// 获取除自身及子节点外的分类
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTreez(string id)
    {
        // var trees =await  _service.repo.Context.SqlQueryable<Ztree>
        //         ("select id,pid,name as type from sys_coop_cate order by ornum")
        //     .ToTreeAsync(it => it.children, it => it.pid, null);
        var treeList = await _service.repo.Context
            .Queryable<SysCoopCate>()
            .WhereIF(!string.IsNullOrWhiteSpace(id), t => t.id != id)
            .OrderBy(it => it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    /// <summary>
    /// 获取分类treeTable数据
    /// </summary>
    [QueryParameters]
    public async Task<dynamic> GetTree(string name)
    {
        var treeList = await _service.repo.Context
            .Queryable<SysCoopCate>()
            .Includes(t => t.crman)
            .Includes(t => t.upman)
            .WhereIF(!string.IsNullOrWhiteSpace(name), t => t.name.Contains(name.Trim()))
            .OrderBy(it => it.ornum)
            .ToTreeAsync(it => it.children, it => it.pid, null);
        return treeList;
    }

    /// <summary>
    /// 获取单个分类详细信息
    /// </summary>
    public async Task<SysCoopCate> GetOne(string id)
    {
        return await _service.Select(id);
    }

    /// <summary>
    /// 新增分类
    /// </summary>
    public async Task Post(SysCoopCate cate)
    {
        await _service.Insert(cate);
    }

    /// <summary>
    /// 更新分类
    /// </summary>
    public async Task Put(SysCoopCate cate)
    {
        await _service.Update(cate);
    }

    /// <summary>
    /// 删除分类
    /// </summary>
    public async Task Delete(string ids)
    {
        var idArr = ids.Split(",");
        foreach (var id in idArr)
        {
            var count = await
                _service.repo.Context.Queryable<SysCoopCate>().Where(it => it.pid == id).CountAsync();
         
            if (count > 0)
            {
                throw new Exception("有子分类无法删除");
            }
        }
        await _service.DeleteAsync(ids);
        await _service.repo.Context.Deleteable<SysOrg>().In(ids).ExecuteCommandAsync();
    }
}